package com.zb.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zb.entity.TbSeckillGoodsModel;
import com.zb.service.TbSeckillGoodsService;
import com.zb.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * <p>添加描述信息</p>
 *
 * @author 李柯
 * @since 2022年11月16日 13:48
 */
@Component
public class MyTask {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TbSeckillGoodsService tbSeckillGoodsService;


    @Scheduled(cron = "0/360 * * * * ?")
    public void init() {
        System.out.println("开启定时任务....");
        List<Date> dateMenus = DateUtil.getDateMenus();
        for (Date date : dateMenus) {
            String extName = DateUtil.data2str(date, DateUtil.PATTERN_YYYYMMDDHH);
            System.out.println("==================>" + extName);
            QueryWrapper<TbSeckillGoodsModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(TbSeckillGoodsModel::getStartTime, date)
                    .eq(TbSeckillGoodsModel::getEndTime, DateUtil.addDateHour(date, 2))
                    .eq(TbSeckillGoodsModel::getStatus, "1")
                    .gt(TbSeckillGoodsModel::getStockCount, 0);

            Set keys = redisTemplate.boundHashOps("seckillGoods:" + extName).keys();
            if (keys != null && keys.size() > 0) {
                queryWrapper.lambda().notIn(TbSeckillGoodsModel::getId, keys);
            }
            List<TbSeckillGoodsModel> list = tbSeckillGoodsService.list(queryWrapper);
            for (TbSeckillGoodsModel goodsModel : list) {
                System.out.println(goodsModel);
                redisTemplate.boundHashOps("seckillGoods:" + extName).put(goodsModel.getId().toString(), goodsModel);
                Long[] ids = this.ids(goodsModel.getStockCount(), goodsModel.getId());
                redisTemplate.boundListOps("seckillGoodsCountList:"+goodsModel.getId()).leftPushAll(ids);
            }
        }
    }
    public Long[] ids(Integer num,Long id){
        Long[] data = new Long[num];
        for (Integer i = 0; i < num; i++) {
            data[i]=id;
        }
        return data;
    }
}
